package com.reactor.demo;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @author jing
 * @description
 * @date 2018/12/8 0008 15:59
 */
public class CountDownLatchDemo {

    public static void main(String[] args) throws InterruptedException {
        /**
         * CountDownLatch类似计数器，可以通过该类指定线程的执行顺序
         */
        final CountDownLatch latch = new CountDownLatch(2);//参数count为计数值

        new Thread(){
            public void run(){
                try {
                    System.out.println("子线程：" + Thread.currentThread().getName() + "正在执行");
                    Thread.sleep(3000);
                    System.out.println("子线程：" + Thread.currentThread().getName() + "子线程执行完毕");
                    latch.countDown();//将计数器的值减1
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        new Thread(){
            public void run(){
                try {
                    System.out.println("子线程：" + Thread.currentThread().getName() + "正在执行");
                    Thread.sleep(3000);
                    System.out.println("子线程：" + Thread.currentThread().getName() + "子线程执行完毕");
                    latch.countDown();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        System.out.println("等待两个线程执行完毕");
        latch.await();//调用该方法会将线程挂起直到计数器count的值为0时继续执行
        System.out.println("两个线程执行完毕");
        System.out.println("继续执行主线程");
    }
}
